package com.jrx.anytxn.reporting.job.xib.config;

import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.utils.BizTypeProducts;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.CmInteCoLonInfo;
import com.jrx.anytxn.reporting.entity.CmInteCoLonInfoBean;
import com.jrx.anytxn.reporting.entity.LoanAcctVo;
import com.jrx.anytxn.reporting.job.xib.step.CustBalHandleProcessor;
import com.jrx.anytxn.reporting.job.xib.step.CustBalHandleWriter;
import com.jrx.anytxn.reporting.job.xib.step.LonInfoListener;
import com.jrx.anytxn.reporting.job.xib.step.LonInfoProcessor;
import com.jrx.anytxn.reporting.job.xib.step.LonInfoWriter;
import com.jrx.anytxn.reporting.job.xib.step.LonInfoXajProcessor;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成贷款信息
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateLonInfoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateLonInfoConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private LonInfoProcessor lonInfoProcessor;
    @Autowired
    private CustBalHandleProcessor custBalHandleProcessor;
    @Autowired
    private LonInfoXajProcessor lonInfoXajProcessor;
    @Autowired
    private LonInfoWriter lonInfoWriter;
    @Autowired
    private CustBalHandleWriter custBalHandleWriter;
    @Autowired
    private LonInfoListener lonInfoListener;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Bean
    public Job generateLonInfoJob() {
        return jobBuilderFactory.get("generateLonInfoJob")
                .start(custBalHandleStep()).incrementer(new RunIdIncrementer()).listener(lonInfoListener)
                .next(generateLonInfoStep())
                .next(generateLonInfoXajStep())
                .build();
    }

    @Bean
    public Step custBalHandleStep(){
        return stepBuilderFactory.get("generateLonInfoStep")
                .<LoanAcctVo, AmLoanAccountInfo>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(custBalHandleReader())
                .processor(custBalHandleProcessor)
                .writer(custBalHandleWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    public Step generateLonInfoStep(){
        return stepBuilderFactory.get("generateLonInfoStep")
                .<CmCustomerFirstLevel, CmInteCoLonInfoBean>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(lonInfoFileReader())
                .processor(lonInfoProcessor)
                .writer(lonInfoWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    /**
     * @description: 生成贷款信息  (兴安借)
     * @author: shigongtai
     * @date: 2023/4/13 14:29
     */
    @Bean
    public Step generateLonInfoXajStep(){
        return stepBuilderFactory.get("generateLonInfoStep")
                .<CmInteCoLonInfo, CmInteCoLonInfoBean>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(loanInfoXajReader())
                .processor(lonInfoXajProcessor)
                .writer(lonInfoWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<CmInteCoLonInfo> loanInfoXajReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        MyBatisCursorItemReader<CmInteCoLonInfo> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        //兴安借替换 用getAllLoanInfoCiWithProducts 替换 getAllLoanInfoCi
        cursorItemReader.setQueryId("com.jrx.anytxn.reporting.mapper.ext.ExtFtpInteCoLonMapper.getAllLoanInfoWithProducts");
        Map<String, Object> map = new HashMap<>();
        map.put("accountStatus", Arrays.asList(ReportingConstant.ACCOUNT_STATUS_1, ReportingConstant.ACCOUNT_STATUS_2));
        map.put("payOffStatus", Arrays.asList(ReportingConstant.ACCOUNT_STATUS_6, ReportingConstant.ACCOUNT_STATUS_7, ReportingConstant.ACCOUNT_STATUS_8, ReportingConstant.ACCOUNT_STATUS_9));
        map.put("loanTypes", Collections.singletonList(TransBizConstant.LOAN_TYPE_7));
        map.put("today", org.getToday());
        map.put("productIds", BizTypeProducts.getXAJSeriesProducts());
        cursorItemReader.setParameterValues(map);
        SynchronizedItemStreamReader<CmInteCoLonInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<LoanAcctVo> custBalHandleReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        MyBatisCursorItemReader<LoanAcctVo> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.reporting.mapper.ext.ExtFtpInteCoLonMapper.getLoanAcctByZero");
        Map<String, Object> map = new HashMap<>();
        map.put("accountStatus", ReportingConstant.ACCOUNT_STATUS_9);
        map.put("tenantId", org.getTenantId());
        map.put("businessDate", org.getToday());
        cursorItemReader.setParameterValues(map);
        SynchronizedItemStreamReader<LoanAcctVo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<CmCustomerFirstLevel> lonInfoFileReader() {
        MyBatisCursorItemReader<CmCustomerFirstLevel> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper.selectAllCust");
        SynchronizedItemStreamReader<CmCustomerFirstLevel> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }
}
